<template>
  <a-card
    style="width: 100%"
    :tab-list="tabListNoTitle"
    :active-tab-key="noTitleKey"
    @tabChange="(key) => onTabChange(key)"
  >
    <span slot="run"> <a-icon type="caret-right" />进行中</span>
    <span slot="stop"> <a-icon type="stop" />已结束</span>
    <div class="table-page-search-wrapper">
      <a-form layout="inline" class="formArea">
        <a-collapse v-model="collapseKey" class="collapseArea" expandIconPosition="right">
          <a-collapse-panel key="1">
            <div slot="header" class="collapseArea_header">
              <a-row :gutter="48">
                <a-col @click.stop="() => {}" v-show="queryParam.history == false" :md="6" :sm="24">
                  <a-form-item label="状态">
                    <a-select v-model="queryParam.state" placeholder="请选择状态" allowClear>
                      <a-select-option value="0"> 全部 </a-select-option>
                      <a-select-option value="1"> 在办 </a-select-option>
                      <a-select-option value="2"> 挂起 </a-select-option>
                    </a-select>
                  </a-form-item></a-col
                >
                <a-col :md="6" :sm="24">
                  <a-form-item label="申请编号">
                    <a-input
                      v-model="queryParam.applyno"
                      placeholder="请输入申请编号"
                      @click.stop="() => {}"
                      allowClear
                    /> </a-form-item
                ></a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="案号">
                    <a-input
                      v-model="queryParam.acceptcode"
                      placeholder="请输入案号"
                      @click.stop="() => {}"
                      allowClear
                    /> </a-form-item
                ></a-col>
                <a-col :md="6" :sm="24">
                  <a-button type="primary" @click.stop="searchData()" icon="search">查询</a-button>
                  <a-button icon="reload" style="margin-left: 8px" @click.stop="reQuery">重置</a-button>
                </a-col>
              </a-row>
            </div>
            <a-row :gutter="48" class="collapseArea_body">
              <a-col :md="6" :sm="24">
                <a-form-item label="申请人">
                  <a-input
                    v-model="queryParam.applyname"
                    placeholder="请输入申请人名称"
                    @click.stop="() => {}"
                    allowClear
                  /> </a-form-item
              ></a-col>
              <a-col v-show="queryParam.history == false" :md="6" :sm="24">
                <a-form-item label="当前环节">
                  <a-select v-model="queryParam.category" placeholder="请选择流程环节" allowClear>
                    <a-select-option v-for="(value, key) in Tp_categoryName" :key="key" :value="key">
                      {{ value }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col v-show="queryParam.history == false" :sm="24" :lg="12" :xl="12">
                <a-form-item label="开始时间">
                  <a-date-picker
                    v-model="tiemQuery.subtime"
                    :show-time="{ defaultValue: this.$moment('00:00:00', 'HH:mm:ss') }"
                    allowClear
                  />
                  ~
                  <a-date-picker
                    v-model="tiemQuery.subtime_01"
                    :show-time="{ defaultValue: this.$moment('23:59:59', 'HH:mm:ss') }"
                    :allowClear="false"
                  /> </a-form-item
              ></a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form>
    </div>

    <a-table
      :scroll="{ x: 1500, y: 500 }"
      :columns="columns"
      :data-source="udata"
      :pagination="upagination"
      :loading="loading"
      rowKey="index"
      @change="tableChange"
      size="middle"
      :bordered="ubordered"
      :rowClassName="rowClassName"
    >
      <template slot="serial" slot-scope="text, record, index">
        {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
      </template>
      <!-- 时间 -->
      <template slot="time" slot-scope="text">
        {{ text ? $moment(text).format('YYYY-MM-DD HH:mm:ss') : '' }}
      </template>
      <!-- 申请产品插槽 -->
      <div slot="prodsSlot" slot-scope="prods" class="overBox" style="width: 100%">
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>{{ prods }}</span>
          </template>
          {{ prods }}
        </a-tooltip>
      </div>
      <!-- 用户tag -->
      <template slot="user" slot-scope="text" v-if="text">
        <a-tag>
          <a-icon type="user" />
          {{ text }}
        </a-tag>
      </template>
      <!-- 用户tag -->
      <template slot="currentuser" slot-scope="text, record">
        <a-tag v-if="text || record.assigneeS"><a-icon type="user" />{{ text ? text : record.assigneeS }} </a-tag>

        <a-tooltip v-else-if="record.currentgroup" placement="topLeft">
          <template slot="title">
            {{ record.groupname }}
          </template>
          <a-tag><a-icon type="team" />{{ record.currentgroup }} </a-tag>
        </a-tooltip>
        <span v-else> 未知 </span>
      </template>
      <!-- 状态 -->
      <template slot="status" slot-scope="text" v-if="text != ''">
        <a-tag :color="text == 1 ? 'blue' : 'orange'">
          {{ text == 1 ? '在办' : '挂起' }}
        </a-tag>
      </template>
      <!-- 业务名称 -->
      <template slot="businessnameSlot" slot-scope="text">
        <div class="beyond_hiding">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>{{ text }}</span>
            </template>
            {{ text }}
          </a-tooltip>
        </div>
      </template>
      <!-- 申请编号 -->
      <template slot="applynoSlot" slot-scope="text">
        <div class="beyond_hiding">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>{{ text }}</span>
            </template>
            {{ text }}
          </a-tooltip>
        </div>
      </template>
      <!-- 案号 -->
      <template slot="acceptcodeSlot" slot-scope="text">
        <div class="beyond_hiding">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>{{ text }}</span>
            </template>
            {{ text }}
          </a-tooltip>
        </div>
      </template>
      <!-- 耗时 -->
      <template slot="durationSlot" slot-scope="text">
        {{ text | timeConsuming }}
      </template>
      <!-- 操作 -->
      <template slot="operation" slot-scope="text, record">
        <a @click="handleEdit(record, 4)">详情</a>
        <template v-if="queryParam.history == false">
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">操作<a-icon type="down" /> </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm
                  :title="record.status === 1 ? '确认挂起吗？' : '确认激活吗？'"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="outOfProcess(record)"
                >
                  <a-icon slot="icon" type="delete" />
                  <a>{{ record.status === 1 ? '挂起' : '激活' }}</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleJump(record, false)">跳转</a>
              </a-menu-item>
              <a-menu-item v-if="record.status == 1">
                <a @click="handleEdit(record, 5)">处理</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </template>
    </a-table>

    <!-- 跳转弹出层 -->
    <a-modal v-model="jumpObj.isModel" width="40%" title="业务跳转">
      <a-select v-model="jumpObj.stepid" style="width: 100%; margin-bottom: 20px" placeholder="请选择跳转节点">
        <a-select-option v-for="item in jumpObj.nodeList" :key="item.id" :value="item.id">
          {{ item.name }} <span v-if="item.documentation">- {{ item.documentation }} </span>
        </a-select-option>
      </a-select>
      <a-textarea v-model="jumpObj.remark" class="textareaBox" :placeholder="`请填写跳转原因`" :max-length="300" />
      <template slot="footer">
        <a-button @click="handleJump(jumpObj, true)" class="btnMargin" type="primary" :loading="btnLoading" icon="check"
          >确定
        </a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<style scoped></style>

<script>
import { findList } from '@/api/worktasks/wt_processStatisticsQuery.js'
import { findDefinitionNodeList } from '@/api/workflow/wf_ProcessDefinition.js'
import { backProcess } from '@/api/workflow/mf_MyTaskUndo.js'
import { APP_USER, APP_DEPT } from '@/store/mutation-types'
import storage from 'store'
import { Tp_categoryValue, Tp_categoryName } from '@/enumeration/Tp_category.js'
import { outProcess } from '@/api/workflow/wf_MyStartInstance'
import { getProcessExecut } from '@/api/workflow/wf_ProcessInstance.js'

export default {
  data() {
    return {
      btnLoading: false, // 按钮加载状态
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      tiemQuery: {
        subtimeStart: undefined,
        subtimeEnd: undefined,
      }, // 时间查询条件
      collapseKey: [], // 折叠面板key
      Tp_categoryName: Tp_categoryName, // 环节分类枚举
      Tp_categoryValue: Tp_categoryValue, // 流程环节标识
      jumpObj: {
        stepid: undefined, // 要跳转到的目标stepid
        taskid: null, // 点击弹框前的临时变量
        nodeList: [], // 跳转节点列表
        isModel: false, // 弹出框状态
        remark: undefined, // 跳转意见
      }, // 跳转对象
      loading: false, // 遮罩是否显示
      visible: false, // 抽屉是否可见
      ubordered: false, // 表格边框是否显示
      isView: false, // 是否查看
      queryParam: {
        pageSize: 20,
        pageNumber: 1,
        history: false,
        state: '0',
      }, // 查询条件
      selectedRowKeys: [], // 选中的行id
      udata: [], // 表格数据
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: (total) => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      columns: [],
      ecolumns: [
        {
          title: '序号',
          width: '50px',
          align: 'center',
          fixed: 'left',
          scopedSlots: { customRender: 'serial' },
        },
        {
          title: '申请人',
          dataIndex: 'applyname',
          width: '90px',
          sorter: (a, b) => String(a.applyname).localeCompare(String(b.applyname)),
          align: 'center',
        },
        {
          title: '业务名称',
          dataIndex: 'businessname',
          align: 'center',
          width: '190px',
          scopedSlots: { customRender: 'businessnameSlot' },
        },
        {
          title: '申请编号',
          dataIndex: 'applycode',
          align: 'center',
          sorter: (a, b) => String(a.applyno).localeCompare(String(b.applyno)),
          width: '150px',
          scopedSlots: { customRender: 'applynoSlot' },
        },
        {
          title: '案号',
          dataIndex: 'acceptcode',
          align: 'center',
          sorter: (a, b) => String(a.acceptcode).localeCompare(String(b.acceptcode)),
          width: '240px',
          scopedSlots: { customRender: 'acceptcodeSlot' },
        },
        {
          title: '当前环节',
          dataIndex: 'linkname',
          align: 'center',
          ellipsis: true,
        },

        {
          title: '接收员',
          dataIndex: 'startuser',
          align: 'center',
          width: '120px',
          scopedSlots: { customRender: 'user' },
        },
        {
          title: '当前处理人',
          dataIndex: 'currentuser',
          width: '240px',
          align: 'center',
          scopedSlots: { customRender: 'currentuser' },
        },
        {
          title: '开始时间',
          dataIndex: 'starttime',
          align: 'center',
          width: '170px',
          sorter: (a, b) => (new Date(a.starttime).getTime() > new Date(b.starttime).getTime() ? 1 : -1),
          scopedSlots: { customRender: 'time' },
        },
        {
          title: '最后处理人',
          dataIndex: 'lastassignee',
          align: 'center',
          width: '140px',
          scopedSlots: { customRender: 'user' },
        },
        {
          title: '最后处理时间',
          dataIndex: 'lasttime',
          align: 'center',
          width: '170px',
          scopedSlots: { customRender: 'time' },
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
        },
      ], // 运行中表头
      hcolumns: [
        {
          title: '序号',
          width: '50px',
          align: 'center',
          fixed: 'left',
          scopedSlots: { customRender: 'serial' },
        },
        {
          title: '申请人',
          dataIndex: 'applyname',
          width: '250px',
          sorter: (a, b) => String(a.applyname).localeCompare(String(b.applyname)),
          align: 'center',
        },
        {
          title: '业务名称',
          dataIndex: 'businessname',
          align: 'center',
          width: '230px',
          scopedSlots: { customRender: 'businessnameSlot' },
        },
        {
          title: '申请编号',
          dataIndex: 'applycode',
          align: 'center',
          sorter: (a, b) => String(a.applyno).localeCompare(String(b.applyno)),
          width: '120px',
          scopedSlots: { customRender: 'applynoSlot' },
        },
        {
          title: '案号',
          dataIndex: 'acceptcode',
          align: 'center',
          sorter: (a, b) => String(a.acceptcode).localeCompare(String(b.acceptcode)),
          width: '200px',
          scopedSlots: { customRender: 'acceptcodeSlot' },
        },
        {
          title: '申请产品',
          dataIndex: 'prods',
          width: '250px',
          align: 'center',
          scopedSlots: { customRender: 'prodsSlot' },
        },
        {
          title: '接收员',
          dataIndex: 'startuser',
          align: 'center',
          width: '100px',
          scopedSlots: { customRender: 'user' },
        },
        {
          title: '开始时间',
          dataIndex: 'starttime',
          align: 'center',
          width: '150px',
          sorter: (a, b) => (new Date(a.starttime).getTime() > new Date(b.starttime).getTime() ? 1 : -1),
          scopedSlots: { customRender: 'time' },
        },
        {
          title: '结束时间',
          dataIndex: 'endtime',
          align: 'center',
          width: '150px',
          sorter: (a, b) => (new Date(a.endtime).getTime() > new Date(b.endtime).getTime() ? 1 : -1),
          scopedSlots: { customRender: 'time' },
        },
        {
          title: '总耗时',
          dataIndex: 'duration',
          width: '150px',
          align: 'center',
          sorter: (a, b) => (Number(a.duration) > Number(b.duration) ? 1 : -1),
          scopedSlots: { customRender: 'durationSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
        },
      ], // 已结束 表头
      tabListNoTitle: [
        {
          key: '1',
          //   tab: '进行中',
          scopedSlots: { tab: 'run' },
        },
        {
          key: '2',
          //   tab: '已结束',
          scopedSlots: { tab: 'stop' },
        },
      ],
      noTitleKey: '1',
    }
  },
  created() {
    console.log('this.$route.query.queryParam.created', this.$route.query.queryParam)
    let routeParam
    try {
      routeParam = JSON.parse(JSON.stringify(this.$route.query.queryParam))
      this.queryParam = { ...this.queryParam, ...this.$route.query.queryParam }
    } catch {
      console.log('路由传参非json格式')
    }

    // 回显查询参数
    if (this.$route.query.queryParam && typeof this.$route.query.queryParam != 'string') {
      this.queryParam = this.$route.query.queryParam
      this.noTitleKey = this.$route.query.queryParam.noTitleKey || '1'
    }
    // 已处理人员
    // this.queryParam.userid = this.currentUser.userId // this.currentUser.username
    this.findWt_ProcessQueryList(this.queryParam)
  },
  methods: {
    // 表格样式
    rowClassName(record, index) {
      return index % 2 === 0 ? 'oddRow' : 'evenRow'
    },
    // 流程实例挂起
    outOfProcess(record) {
      console.log('record', record)
      const savem = this.$message.loading('正在执行操作，请稍后...', 0)
      outProcess({
        handletext: record.status === 1 ? '挂起' : '激活',
        processinstanceid: record.processinstanceid,
        userid: this.currentUser.userId,
        suspensionState: record.status === 1 ? 1 : 2,
        taskid: record.taskid
      })
        .then((res) => {
          if (res.code === 0 && res.data.code == 0) {
            this.$message.success(res.data.msg)
            this.findWt_ProcessQueryList(this.queryParam)
          } else {
            this.$message.warning(res.data.msg)
          }
        })
        .finally(() => {
          setTimeout(savem, 0)
        })
    },
    // 跳转到指定节点
    handleJump(record, status) {
      if (status) {
        if (!this.jumpObj.stepid) {
          this.$message.warning('请选择跳转节点')
          return
        } else if (!this.jumpObj.remark) {
          this.$message.warning('请填写跳转原因')
          return
        }
        this.btnLoading = true
        const savem = this.$message.loading('正在执行操作，请稍后...', 0)
        backProcess({ handletext: '跳转', userid: this.currentUser.userId }, record)
          .then((res) => {
            console.log('跳转节点', res)
            if (res.code == 0 && res.data.code == 0) {
              this.$message.success('操作成功')
              this.jumpObj.isModel = false
              this.findWt_ProcessQueryList(this.queryParam)
            } else {
              this.$message.warning(res.data.msg)
            }
          })
          .finally(() => {
            this.btnLoading = false
            setTimeout(savem, 0)
          })

        console.log('开始跳转', record)
      } else {
        this.jumpObj.taskid = record.taskid
        this.jumpObj.remark = undefined
        this.jumpObj.stepid = undefined
        this.loading = true
        findDefinitionNodeList(record.processdefinitionid)
          .then((res) => {
            console.log('跳转节点', res)
            if (res.code == 0) {
              this.jumpObj.nodeList = res.data || []
              this.jumpObj.isModel = true
            }
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    /**
     * 进入编辑页面
     */
    async handleEdit(record, pattern) {
      console.log('预览参数', record)
      let taskid = record.taskid
      if (this.queryParam.history) {
        let res = await getProcessExecut(record.processinstanceid)
        console.log('执行实例', res)
        if (res.code == 0) {
          taskid = res.data.id
        }
      }
      if (taskid) {
        this.queryParam.noTitleKey = this.noTitleKey
        this.$router.push({
          name: `Wf_MyTaskUndoOperationQuery`,
          params: { taskid: taskid, pattern: pattern },
          query: {
            url: '/wt_ProcessQuery',
            queryParam: this.queryParam,
          },
        })
      } else {
        this.$message.error('未找到taskid')
      }
    },
    // 标签页切换
    onTabChange(key) {
      if (key == '1') {
        this.queryParam.history = false
      } else if (key == '2') {
        this.queryParam.history = true
      }
      this.noTitleKey = key
      this.reQuery()
    },
    /**
     *  查询已处理业务列表
     */
    findWt_ProcessQueryList(queryParam) {
      this.loading = true
      const a = Date.now()
      if (queryParam.history) {
        this.columns = this.hcolumns
      } else {
        this.columns = this.ecolumns
      }
      findList(queryParam).then((res) => {
        console.log('表格数据', res)
        if (res.code == 0 && res.data && res.data.records) {
          this.udata = res.data.records
          // 将当前页码和数量与后台绑定
          this.upagination.total = res.data.total
          this.upagination.current = this.queryParam.pageNumber
          this.upagination.pageSize = this.queryParam.pageSize
        }
        // 如果查询时间太短就给一个0.5秒的加载效果
        const b = Date.now()
        if (b - a < 500) {
          setTimeout(() => {
            this.loading = false
          }, 500)
        } else {
          this.loading = false
        }
      })
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery() {
      let history = this.queryParam.history
      this.queryParam = {}
      this.queryParam.state = '0'
      this.queryParam.history = history
      this.tiemQuery.subtime = null
      this.tiemQuery.subtime_01 = null
      this.queryParam.userid = this.currentUser.userId
      this.queryParam.pageNumber = 1
      this.queryParam.pageSize = 20
      this.findWt_ProcessQueryList(this.queryParam)
    },
    /**
     * 翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
     */
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      this.queryParam.pageNumber = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      if (sorter != null && sorter.order != null) {
        this.queryParam.sort = sorter.field
        this.queryParam.order = sorter.order
      }
      this.findWt_ProcessQueryList(this.queryParam)
    },
    /**
     * 查询
     */
    searchData() {
      // 查询时将当前页码重置为1，否则会出现有数据但不显示的问题
      this.queryParam.pageNumber = 1
      if (this.tiemQuery.subtime) {
        // this.queryParam.subtime = this.queryParam.subtime.format('YYYY-MM-DD')
        this.queryParam.subtimeStart = this.tiemQuery.subtime.valueOf()
      }
      if (this.tiemQuery.subtime_01) {
        // this.queryParam.subtime_01 = this.queryParam.subtime_01.format('YYYY-MM-DD')
        this.queryParam.subtimeEnd = this.tiemQuery.subtime_01.valueOf()
      }
      this.findWt_ProcessQueryList(this.queryParam)
    },
  },
}
</script>
<style lang="less" scoped>

::v-deep .ant-table-thead > tr > th{
  font-weight: 600;
}
.beyond_hiding {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.formArea {
  margin-bottom: 30px;
}
/deep/ .ant-collapse-header {
  background-color: #fff;
}
.collapseArea {
  border: none;
  .ant-collapse-item {
    border-bottom: none;
  }
  /deep/.ant-collapse-content {
    border-top: none;
  }
}

.collapseArea_header {
  .ant-form-item {
    margin-bottom: 0;
  }
}

.collapseArea_body {
  padding-top: 10px;
  padding: 0 20px 0 0px;
}

.breathingLampState {
  float: left;
  margin-left: 20px;
}
@keyframes scaless {
  0% {
    transform: scale(1);
  }

  50%,
  75% {
    transform: scale(3);
  }

  78%,
  100% {
    opacity: 0;
  }
}
.textareaBox {
  height: 150px;
  /* margin-top: 20px; */
}
</style>
